/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author carolina
 */
class LibraryMain {

    private boolean analyzed = false
    def allbook = null;
    def idSession = null;

    def getNextBook = { login, pass  ->
         try {
            if (analyzed) {
             } else {               
                allbook = conectaEmbeddedLibrary("http://tomcat.embedded.ufcg.edu.br/library/wSRestLibrary/authentication?login=" + login + "&password=" + pass)
                analyzed = true                
             }
             if (allbook.size() == 0){
                 allbook = "Você não tem livros!"
             }           
           return allbook
         } catch (Exception e) {
             println "Message: " + e.getMessage()
             return  "Você não tem livros!"
         }
    }

    private def conectaEmbeddedLibrary = { content ->
        def text = getContent(content)
        idSession = getIdSession(text)
        println "librarySession="+idSession
        //def result = this.getBooks("http://tomcat.embedded.ufcg.edu.br/library/wSRestLibrary/getPendingLoaningsByUser?sessionId=" + idSession)
        def result = this.getBooks("src/library/getLoaningsByUserOk.xml")
        newsLogout()
        return result
    }

    private def getContent = { connect ->
        def url = new URL(connect)
        def connection = url.openConnection()
        connection.setRequestMethod("POST")
        connection.connect()

        def result = ""
        if (connection.responseCode != 200) {
            result = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><WSResultsRestLibrary><class>WSResultsRestLibrary</class><error>Bad Reponse</error><sessionID/><sucessMessage/></WSResultsRestLibrary>"
        } else {
            result = connection.content.text
       }       
       return result
    }

    private def getIdSession = { content ->
        def xml = new XmlParser().parseText(content)
        def result = "-1"
        xml.each {
            if (it.name() == "sessionID" ) {
                result = it.text()
            }
        }
        return result
    }

    private def getBooks = { content ->
        //def text = getContent(content)
        //def xml = new XmlParser().parseText(text)        
        def xml = new XmlParser().parse(content)        
        def result = "";
        if (xml.class.text() == "WSResultsRestLibrary" ) {
            println "xml.error.text()=" + xml.error.text()
            result = "Você não tem livros!"
        } else {            
            xml.loaning.each {
              //  def result1 = getBookById("http://tomcat.embedded.ufcg.edu.br/library/wSRestLibrary/getBookById?sessionId="
              //                              + idSession + "&bookId="+ it.book.'@id'[0])
                def result1 = getBookById("src/library/getBookByIdOk.xml", it.book.'@id'[0])
                def result2 = it.loaningDate.text()
                result = result + "<p></p> Você esta com o livro <strong>" + result1 + "</strong> desde " + result2                
            }
        }        
        return result
    }

    def searchBook = { search ->
        def text = getContent(http://tomcat.embedded.ufcg.edu.br/library/wSRestLibrary/logout?sessionId="
                                + idSession + "&q=" + search)
        def book = new XmlParser().parseText(text)

         if (book.class.text() == "WSResultsRestLibrary" ) {
            //throw new Exception(book.error.text())
        } else {
            def result = ""
            book.each {
                if (it.name() == "publicationYear") {
                   result = it.text()
                }
                if (it.name() == "title") {
                   result = it.text() + ": " + result
                }
            }
            return result
        }           
    }

    def private newsLogout = {
       def text = getContent("http://tomcat.embedded.ufcg.edu.br/library/wSRestLibrary/logout?sessionId="
                                + idSession)
       def xml = new XmlParser().parseText(text)
       if (xml.class.text() == "WSResultsRestLibrary" ) {            
       }
    }

   private def getBookById = { content ->        
        def text = getContent(content)
        //def book = new XmlParser().parseText(text)
        def book = new XmlParser().parse(content)

        if (book.class.text() == "WSResultsRestLibrary" ) {            
            //throw new Exception(book.error.text())
        } else {           
            def result = ""
            book.each {
                if (it.name() == "publicationYear") {
                   result = it.text()
                }
                if (it.name() == "title") {
                   result = it.text() + ": " + result                   
                }
            }
            return result
        }                
   }
}

